//
//  PPAccomplishViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/23/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAccomplishViewController.h"
#import "PPHomeViewController.h"
#import "PPNetworkService.h"
#import "PPHomeNavigationController.h"

@interface PPAccomplishViewController () <UITextFieldDelegate,TZImagePickerControllerDelegate>
//@property (weak, nonatomic) IBOutlet UITextField *nickField;
//@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (readwrite, nonatomic, strong) UIButton *hiddenButton;
@property (readwrite, nonatomic, strong) UIButton *finishButton;
@property (readwrite, nonatomic, strong) UIView *bottomView;

@property (nonatomic,strong) UIImageView *photoView;
@property (strong, nonatomic) IBOutlet UITextField *nickField;

@end

@implementation PPAccomplishViewController
//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
     [self.navigationController setNavigationBarHidden:NO animated:YES];
}

///MARK:选择上传头像
- (void)selectPhoto{

    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.allowPickingVideo = NO;
    WEAKSELF
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        if (photos.count > 0) {
            weakSelf.photoView.image = photos[0];
           [self.navigationController.view toastMessage:@"头像设置成功"];
            
        }else{
            [self.navigationController.view toastMessage:@"超时，请重试！"];
        }
        [self.nickField becomeFirstResponder];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


- (UIImageView *)photoView{
    if (!_photoView) {
        _photoView = [[UIImageView alloc] init];
        _photoView.bounds = CGRectMake(0, 0, 90, 90);
        _photoView.center = CGPointMake(self.view.width/2,164);
        _photoView.image = [UIImage imageNamed:@"person_normal"];
        _photoView.layer.masksToBounds = YES;
        _photoView.layer.cornerRadius = 45;
        _photoView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectPhoto)];
        [_photoView addGestureRecognizer:tap];
    }
    return _photoView;
}
- (UITextField *)nickField{

    if (!_nickField ) {
        _nickField = [[UITextField alloc] initWithFrame:CGRectMake(15,CGRectGetMaxY(self.photoView.frame)+28,self.view.width-2*15,27)];
        _nickField.placeholder = @"设置昵称";
        _nickField.font = PPFONTSIZE(17.0);
        _nickField.textColor = COLORA(153, 153, 153);
        _nickField.textAlignment = NSTextAlignmentCenter;
        _nickField.returnKeyType = UIReturnKeyDone;
        _nickField.delegate = self;
//        _nickField.enablesReturnKeyAutomatically = YES;
    }
    return _nickField;
}
- (void)setupViews{

    [self.view addSubview:self.photoView];
    
    [self.view addSubview:self.nickField];
    
    [_nickField becomeFirstResponder];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupViews];

//    self.title = @"昵称和密码";
//
//    self.view.backgroundColor = [UIColor whiteColor];
//    
//    {
//        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        leftView.backgroundColor = [UIColor clearColor];
//        _nickField.leftView = leftView;
//        _nickField.leftViewMode = UITextFieldViewModeAlways;
//
//        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        rightView.backgroundColor = [UIColor clearColor];
//        _nickField.rightView = rightView;
//        _nickField.rightViewMode = UITextFieldViewModeAlways;
//    }
//
//    {
//        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        leftView.backgroundColor = [UIColor clearColor];
//        _passwordField.leftView = leftView;
//        _passwordField.leftViewMode = UITextFieldViewModeAlways;
//
//        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 48, 46)];
//        rightView.backgroundColor = [UIColor clearColor];
//        _passwordField.rightView = rightView;
//        _passwordField.rightViewMode = UITextFieldViewModeAlways;
//
//        _hiddenButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        _hiddenButton.adjustsImageWhenHighlighted = NO;
//        [_hiddenButton setImage:[UIImage imageNamed:@"code-off"] forState:UIControlStateNormal];
//        [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateHighlighted|UIControlStateSelected];
//        [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateSelected];
//        [_hiddenButton sizeToFit];
//        _hiddenButton.center = CGPointMake(rightView.width/2, rightView.height/2);
//        [_hiddenButton addTarget:self action:@selector(hiddenButtonDidPressed:) forControlEvents:UIControlEventTouchUpInside];
//        [rightView addSubview:_hiddenButton];
//    }

//    _bottomView = [[UIView alloc] init];
//    _bottomView.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:_bottomView];

//    _finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_finishButton setTitle:@"完成" forState:UIControlStateNormal];
//    [_finishButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xffdd17]] stretchableImageByCenter] forState:UIControlStateNormal];
//    [_finishButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xf9d430]] stretchableImageByCenter] forState:UIControlStateHighlighted];
//    [_finishButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xf2f2f2]] stretchableImageByCenter] forState:UIControlStateDisabled];
//    [_finishButton addTarget:self action:@selector(finishButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
//    [_bottomView addSubview:_finishButton];
}


- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

//    _bottomView.frame = CGRectMake(0, self.view.height - 45, self.view.width, 45);

//    _finishButton.frame = _bottomView.bounds;
}
///MARK:完成
- (void)finishButtonDidPressed
{
    [MobClick event:@"9"];

    [self.view endEditing:YES];

    NSString *nickname = @"";
    
    if(_nickField.text.length >0 || [_nickField.text isEqualToString:@""]){
    
        nickname = _nickField.text;
    }
//    NSString *password = _passwordField.text;

    NSRange range = [nickname rangeOfString:@" "];
    if (range.location != NSNotFound) {
        [self.navigationController.view toastMessage:@"昵称不能包含空格哦" duration:1.f];
        return;
    }
    NSInteger count = 0; //汉字
    NSInteger count1 =0; //英文
    for (NSInteger i = 0; i < [nickname length]; i++) {
        unichar c = [nickname characterAtIndex:i];
        if (c >=0x4E00 && c <=0x9FA5)
        {
            count ++;
        }
        else
        {
            count1 ++;

        }
    }
    if (count1 == 0 && count == 0)
    {
        [self.navigationController.view toastMessage:@"昵称至少要包含一个字母或汉字哦" duration:1.f];
        return;
    }
    if (count1 + count*2 > 32)
    {
        [self.navigationController.view toastMessage:@"昵称长度不能超过16哦" duration:1.f];
        return;
    }

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    
    PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
    artwork.uuid = [NSString uuid];
    
    WEAKSELF;
    [PPNetworkService registerWithPhomeNumber:self.phone password:self.pwd name:nickname fileName:artwork.transactionIdentifier callback:^(id data, NSError *error) {
    
//    [PPNetworkService registerWithPhomeNumber:self.phone password:self.pwd name:nickname uploadName:@"picture" uploadDatas:@[self.photoView.image] callback:^(id data, NSError *error) {
        [hud hide:YES];
        
        if(error == nil) {
//            [[MBProgressHUD alloc] toastMessage:@"注册成功"];
            
            [self.navigationController.view toastMessage:@"注册成功" duration:2 completion:^{
            
                DGAccount *account = [[DGAccount alloc] init];
                account.userID = [data validStringForKey:@"user"];
                account.username = nickname;
                //                account.password = password;
                account.credential = [[DGAccountCredential alloc] init];
                account.credential.userID = account.userID;
                account.credential.token = [data validStringForKey:@"token"];
                
                NSDictionary *dict = data;
                
                [[PPUserAccount yy_modelWithDictionary:dict] saveAccount];
                
                [[PPAccountManager sharedInstance] loginWithAccount:account completion:^(BOOL success) {
                    if(success) {
                        PPUploaderFile *file = [PPUploaderFile yy_modelWithDictionary:dict[@"picture"]];
                        file.image = self.photoView.image;
                        file.filename = artwork.transactionIdentifier;
                        //注册成功。。。。
                        PPHomeViewController *homeViewController = [[PPHomeViewController alloc] init];
                        homeViewController.uploadFile = file;
                        PPBaseNavigationViewController *navigationController = [[PPBaseNavigationViewController alloc] initWithRootViewController:homeViewController];
                        [[[UIApplication sharedApplication] delegate] window].rootViewController = navigationController;
                    } else {
                        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    }
                }];
            }];
            
            [MBProgressHUD hideHUD];
            
        } else {
            [weakSelf.navigationController.view toastMessage:error.networkPrompt];
        }

    }];
    
//    [PPNetworkService registerWithPhomeNumber:self.phone password:self.pwd name:nickname callback:^(id data, NSError *error) {
//        __strong typeof(weakSelf) strongSelf = weakSelf;
//        if(strongSelf == nil)
//        {
//            return;
//        }
//
//        [hud hide:YES];
//
//        if(error == nil) {
//            [strongSelf.navigationController.view toastMessage:@"注册成功" duration:2 completion:^{
//
//                DGAccount *account = [[DGAccount alloc] init];
//                account.userID = [data validStringForKey:@"user"];
//                account.username = nickname;
////                account.password = password;
//                account.credential = [[DGAccountCredential alloc] init];
//                account.credential.userID = account.userID;
//                account.credential.token = [data validStringForKey:@"token"];
//
//                [[PPAccountManager sharedInstance] loginWithAccount:account completion:^(BOOL success) {
//                    if(success) {
//                        
//                        //注册成功。。。。
//                        PPHomeViewController *homeViewController = [[PPHomeViewController alloc] init];
//                        PPHomeNavigationController *navigationController = [[PPHomeNavigationController alloc] initWithRootViewController:homeViewController];
//                        [[[UIApplication sharedApplication] delegate] window].rootViewController = navigationController;
//                    } else {
//                        [strongSelf.navigationController popToRootViewControllerAnimated:YES];
//                    }
//                }];
//            }];
//
//        } else {
//            [strongSelf.navigationController.view toastMessage:error.networkPrompt];
//        }
//    }];
}

- (void)hiddenButtonDidPressed:(UIButton *)button
{
    [MobClick event:@"8"];

    button.selected = !button.selected;

//    _passwordField.secureTextEntry = !button.selected;
}


#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if([string isEqualToString:@"\n"])
    {
        if(textField == _nickField)
        {
//            [_passwordField becomeFirstResponder];
        }
        else
        {
            [_finishButton sendActionsForControlEvents:UIControlEventTouchUpInside];
        }

        return NO;
    }

    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    
    if (textField == _nickField) {
        
        [self finishButtonDidPressed];
    }
    
    return YES;
}
@end
